package com.yy.job.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IPUtils {
	
	private static final Logger log = LoggerFactory.getLogger(IPUtils.class);

	public static String getLocalHostName() {
		String localHostName = null;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			localHostName = addr.getHostName();
		} catch (Exception e) {
			log.warn("获取本机名异常：", e);
		}
		return localHostName;
	}

	public static String getLinuxLocalIP() {
		String ip = "";
		try {
			Enumeration<NetworkInterface> e1 = NetworkInterface.getNetworkInterfaces();
			while (e1.hasMoreElements()) {
				NetworkInterface ni = e1.nextElement();
				if ("eth0".equals(ni.getName()) || "bond0".equals(ni.getName())) {
					Enumeration<InetAddress> e2 = ni.getInetAddresses();
					while (e2.hasMoreElements()) {
						InetAddress ia = e2.nextElement();
						if (ia instanceof java.net.Inet6Address)
							continue;
						ip = ia.getHostAddress();
					}
					break;
				}
			}
		} catch (Exception e) {
			log.warn("获取Liunx机器IP异常：", e);
		}
		return ip;
	}

	public static String getWinLocalIP() {
		String ip = null;
		try {
			ip = InetAddress.getLocalHost().getHostAddress().toString();
		} catch (Exception ex) {
			log.warn("获取Window机器IP异常：", ex);
		}
		return ip;
	}

	public static String getLocalIP() {
		String ip = System.getenv("HOST_IP");
		if (StringUtils.isBlank(ip))
			if (!System.getProperty("os.name").contains("Win")) {
				ip = getLinuxLocalIP();
			} else {
				ip = getWinLocalIP();
			}
		return ip;
	}

}
